import React, { createContext, useState, useReducer, useEffect, useCallback } from 'react';
import { createReducerMapper, useMyReducer } from '@/utils/index';
import { MyMessageList_Web, MyMessageList_Res } from '@/pages/_server/_class/MyMessage/MyMessageList';
import { apiGetMessageList } from '@/pages/_server/_api/ApiMessage/apiGetMessageList';
export type MessageContextType = {
    activeIndex: number;
    setActiveIndex: (state: number) => any;
    tabItems: any[];
    swiperRef: any;
};

export const MessageContext = createContext<MessageContextType>(undefined);

/** 处理reducer的函数 */
const handleMapper = createReducerMapper({
    initializer: null,
    handleMapper: {
        /**修改值 */
        setData: (state, payload: { newData: Partial<MessageExhibition> }) => {
            return { ...state, ...payload.newData };
        },
        /**设置为已读 */
        setIsRead: (state, payload?: { id: number }) => {
            let newState: Pick<MessageExhibition, 'MessageList'> = {
                MessageList: [],
            };
            newState.MessageList = state.MessageList.map((item) => {
                if (item.id == payload.id) {
                    item.haveRead = 1;
                }
                return item;
            });
            return { ...state, ...newState };
        },
    },
});

/** 页面渲染的列表 */
export type MessageExhibition = {
    MessageList: MyMessageList_Web[];
    LoadingStatus: 'Loading' | 'complete' | 'nodata';
    pageIndex: number;
};

const initialState: MessageExhibition = {
    MessageList: [
    ],
    LoadingStatus: 'Loading',
    pageIndex: 0,
};

/** 使用需要展示的列表 */
export const useMessageExhibitionList = (status: 'all' | 'Unread') => {
    const [messageExhibitionState, messageExhibitionDispatch] = useMyReducer({
        initializer: initialState,
        handleMapper,
    });
    useEffect(() => {
        let haveRead: 0 | 1 = status === 'all' ? null : 0;
        let searchFrom = {
            haveRead,
            pageIndex: messageExhibitionState.pageIndex,
        };
        // 页面加载完成时初始化列表
        apiGetMessageList(searchFrom).then((res) => {
            if (!res) return;
            freShListState({ LoadingStatus: 'complete', MessageList: res.data });
        });
    }, []);

    /**刷新列表和加载状态 */
    const freShListState = useCallback(
        (params: Partial<MessageExhibition>) => {
            messageExhibitionDispatch({
                type: 'setData',
                payload: {
                    newData: params,
                },
            });
        },
        [messageExhibitionDispatch]
    );

    return {
        messageExhibitionState,
        freShListState,
        messageExhibitionDispatch,
    };
};
